package com.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName copyFileUseNIO
 * @Description TODO
 * @Author zxs
 * @Date 2021/4/1 19:43
 * Version 1.0
 */
/*
* 通过NIO实现文件复制功能
* */
public class copyFileUseNIO {

    public static void main(String[] args) throws IOException {

        //声明源文件和目标文件
        FileInputStream fi = new FileInputStream(new File("E:\\input.txt"));
        FileOutputStream fo = new FileOutputStream("E:\\niofile.txt");

        //获取传输通道channel
        FileChannel inChannel = fi.getChannel();
        FileChannel outChannel = fo.getChannel();

        //获得容器buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while(true){
            //判断是否读完文件
            int eof = inChannel.read(buffer);
            if(eof == -1){
                break;
            }
            //切换buffer模式，即写模式变成读模式或读模式切换写模式
            buffer.flip();

            //开始写
            outChannel.write(buffer);

            //写完要重置buffer
            //buffer.compact();
            buffer.clear();

            //关闭通道
            inChannel.close();
            outChannel.close();
            //关闭流
            fi.close();
            fo.close();
        }
    }
}
